package com.hqbzl.c1.rlock;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//4个线程依次打印ABCD,循环指定次数
@Slf4j
public class SequenceWrite2 {

    public static void main(String[] args) {
        final Writer2 writer = new Writer2(4);
        new Thread(() -> {
            writer.print("a", 0, 1);
        }, "thread-a").start();
        new Thread(() -> {
            writer.print("b", 1, 2);
        }, "thread-b").start();
        new Thread(() -> {
            writer.print("c", 2, 3);
        }, "thread-c").start();
        new Thread(() -> {
            writer.print("d", 3, 0);
        }, "thread-d").start();

    }

    static class Writer2 {
        ReentrantLock room = new ReentrantLock();
        final List<Condition> conditions = new ArrayList<>();

        private void print(String str, int index, int next) {
            room.lock();
            try {
                for (int i = 0; i < num; i++) {
                    // 如果不是当前的，就阻塞
                    while (index != currentIndex) {
                        try {
                            conditions.get(index).await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(str);
                    currentIndex = next;
                    conditions.get(next).signal();
                }
            } finally {
                room.unlock();
            }
        }

        // 当前索引
        private int currentIndex = 0;
        // 循环次数
        private int num;

        public Writer2(int num) {
            for (int i = 0; i < 4; i++) {
                conditions.add(room.newCondition());
            }
            this.num = num;
        }
    }

}
